<template>
  <div v-loading="loading" class="container">
    <div slot="content" class="card-content">
      <div v-if="$route.params.type !== 'detail'" class="title-button">
        <!-- v-if="show && windowValue" -->
        <el-button size="small" @click="back">取消</el-button>
        <!-- <el-button v-if="show && !windowValue" type="primary" size="small" :loading="savaLoading" @click="openDialogVisible">委托/修改</el-button> -->
        <el-button v-if="show" type="primary" size="small" :loading="savaLoading" @click="sava">更新到渠道</el-button>
        <el-button v-if="!show" type="primary" size="small" :loading="submitExamineLoading" @click="submitExamine">提交审核</el-button>
      </div>
      <menuScroll ref="menuScrollRef" @changeLoading="changeLoading" @openDialogVisible="openDialogVisible" />
      <submit-approval-dialog ref="submitApprovalRef" :dialog-loading="dialogLoading" @onsubmit="submitReview" />
    </div>
    <entrusted-modification ref="entrusted" />
  </div>
</template>

<script>
import menuScroll from '@/views/coi/commodityM/components/menuScroll.vue'
import submitApprovalDialog from '@/views/coi/commodityM/components/submitApprovalDialog.vue'
import { commodityInfoSave, submitApproval, saveAndPushSkuInfo, pushSkuInfo } from '@/api/coi/onlineTaskAPI/sku'
import eventBus from '@/utils/eventBus'
import { transSavaData2 } from '@/utils/processingData.js'
import entrustedModification from '@/views/coi/commodityM/components/entrustedModification'
import { goodsTypeList } from '@/views/coi/commonJs/dictionary.js'
export default {
  name: 'CommodityEdit',
  components: {
    menuScroll,
    submitApprovalDialog,
    entrustedModification
  },
  data() {
    return {
      loading: false,
      savaLoading: false,
      submitExamineLoading: false,
      show: this.$route.params.from !== 'OnlineBuildingTasks',
      dialogLoading: false,
      windowValue: window.appConfig.hiddenNewProducts
    }
  },
  computed: {
    // 1 线上商品库， 2 商品维护任务
    requestType() {
      let flag = null
      switch (this.$route.params.from) {
        case 'GoodsLibrary':
          flag = 1
          break
        case 'OnlineBuildingTasks':
          flag = 2
          break
        case 'ChannelInventory':
          flag = 3
          break
        default:
          break
      }
      return flag
    }
  },
  mounted() {
    eventBus.$on('detailChange', (status) => {
      const goodType = this.$refs?.menuScrollRef?.goodsInfo?.goodsType
      if (goodType === 'DROPSHIPPING') return
      this.show = false
    })
    eventBus.$on('loadingChange', (status) => {
      this.loading = status
    })
  },
  methods: {
    changeLoading(value) {
      this.loading = value
    },
    message(message, back = false) {
      this.$message({ message, type: 'success' })
      if (back) {
        this.$router.push({
          name: this.$route.params.from,
          params: { tab: this.$route.query.tab, type: 'sku' }
        })
      }
    },
    sava() {
      const valid = this.validate()
      if (!valid) return this.$message.error('请将信息填写完整和正确，再做提交！')
      this.submit()
    },
    submitExamine() {
      this.$refs.submitApprovalRef.dialogVisible = true
    },
    // 提交审核
    async submitReview(remark) {
      const valid = this.validate()
      if (!valid) return this.$message.error('请将信息填写完整和正确，再做提交！')
      this.loading = true
      const res1 = await this.submit() // sava
      if (!res1) return
      this.dialogLoading = true
      const param = {
        idList: [this.show ? this.$route.params.upc : res1],
        submitTrialRemark: remark
      }
      const _this = this
      submitApproval(param).then((res) => {
        if (res) {
          _this.$refs.submitApprovalRef.dialogVisible = false
          _this.dialogLoading = false
          _this.$message({
            type: 'success',
            message: '提交成功!'
          })
          eventBus.$emit('closeTag', this.$route)
        }
      })
      this.loading = false
    },
    validate() {
      const refsObject = this.$refs.menuScrollRef.$refs
      const refsKey = Object.keys(refsObject)
      const flags = refsKey.map((item) => {
        const selfRef = refsObject[item]
        if (Array.isArray(selfRef)) {
          return selfRef[0].submitForm()
        } else if (selfRef.submitForm) {
          return selfRef.submitForm()
        } else if (this.$refs.menuScrollRef.submitForm) {
          return this.$refs.menuScrollRef.submitForm()
        }
      })
      return flags.every((_) => _)
      // // 说是只要抛红,不阻止往下提交哦
      // return true
    },
    // 保存
    async submit() {
      try {
        this.savaLoading = true
        const info = this.filterSkuInfo2()
        const operationCode = this.$refs.menuScrollRef.operationCode
        const fromPage = this.$route.params.from
        if (!this.show) info.processType = this.$route.params.channelId === '0' ? 1010 : 1030
        if (fromPage === 'GoodsLibrary' || fromPage === 'ChannelInventory') {
          info.operationCode = this.checkOperationCode(operationCode) || info.operationCode
        }
        const goodsPhotos = this.$refs.menuScrollRef.goodsPhotos
        goodsPhotos.skuResourcesImg.forEach((item, index) => {
          item.sort = index
          item.resourceType = 1
        })
        goodsPhotos.skuOptionResources.forEach((item, index) => {
          item.resourceType = 2
        })
        goodsPhotos.transparentImg.forEach((item, index) => {
          item.resourceType = 3
        })
        info.skuChannelInfos[0].skuResources = [...goodsPhotos.skuResourcesImg, ...goodsPhotos.transparentImg]
        info.skuChannelInfos[0].skuOptionResources = goodsPhotos.skuOptionResources
        info.imageUrl = goodsPhotos.skuResourcesImg[0].resourceUrl
        info.skuChannelInfos.forEach((element) => {
          element.skuChannelInfo = JSON.stringify(element)
          if (this.$route.params.channelId === '06') {
            transSavaData2(element.categoryAttributeList, true, false)
            transSavaData2(element.channelAttributeList, true, false)
          }
          if (element.channelBrandName) {
            element.brandName = JSON.parse(JSON.stringify(element.channelBrandName))
            delete element.channelBrandName
          }
          if (this.$route.params.channelId === '0') {
            delete element.categoryAttributeList
            delete element.channelAttributeList
          }
        })
        const goodType = this.$refs?.menuScrollRef?.goodsInfo?.goodsType
        let result = null
        if (!info.giveawayFlag) {
          if ('giveawayEffectiveDate' in info) info.giveawayEffectiveDate = null
          if ('giveawayExpiryDate' in info) info.giveawayExpiryDate = null
        }
        if (this.show && goodType === 'DROPSHIPPING' && this.requestType === 3) {
          const { result: processId } = await commodityInfoSave(info)
          const res = await pushSkuInfo(processId)
          result = res.result
        } else if (this.show) {
          const res = await saveAndPushSkuInfo(info)
          result = res.result
        } else {
          const res = await commodityInfoSave(info)
          result = res.result
        }
        // const { result } = this.show ? await saveAndPushSkuInfo(info) : await commodityInfoSave(info)
        if (result && this.show) {
          this.message('更新到渠道成功！', true)
          eventBus.$emit('closeTag', this.$route)
        }
        this.loading = false
        return result
      } finally {
        this.savaLoading = false
      }
    },
    checkOperationCode(operationCode) {
      let bol = false
      let bol2 = false
      let bol3 = false
      let code = null
      let codes = 0
      operationCode.forEach((item, i) => {
        if (item !== null) {
          code = item
          if (i === 0) {
            bol = true
          }
          if (i === 1 && bol) {
            bol2 = true
            code = 110
          }
          if (i === 2 && bol) {
            bol3 = true
            code = 120
          }
          if (bol2 && bol3) {
            code = 160
          }
          codes++
        }
      })
      if (codes === 3) {
        code = 130
      }
      return code
    },
    filterSkuInfo2() {
      const sku = JSON.parse(JSON.stringify(this.$refs.menuScrollRef.goodsInfo))
      if ('goodsTypeName' in sku) delete sku.goodsTypeName
      if ('saleStatusName' in sku) delete sku.saleStatusName
      if ('returnTypeName' in sku) delete sku.returnTypeName
      if ('returnDescTypeName' in sku) delete sku.returnDescTypeName
      return sku
    },
    back() {
      const type = this.$route.query.tab === 'JDWX' ? 'spu' : 'sku'
      this.$router.push({
        name: this.$route.params.from,
        params: { tab: this.$route.query.tab, type: type }
      })
    },
    openDialogVisible(data) {
      console.log('data', data)
      if (!data.isShow) {
        if (data.goodsType !== '暂无商品类型') return this.$message.error(`${this.setGoodNames(data.goodsType)}商品不允许委托，请重试`)
        else return this.$message.error(`暂无商品类型,请联系管理员`)
      }
      this.$refs.entrusted.dialogVisible = true
      this.$refs.entrusted.getAllData()
    },
    setGoodNames(name) {
      let text = ''
      goodsTypeList.forEach((item) => {
        if (item.value === name) {
          text = item.label
        }
      })
      // switch (name) {
      //   case 'NORMAL':
      //     text = '常规商品'
      //     break
      //   case 'CBEC':
      //     text = '跨境电商'
      //     break
      //   case 'PB':
      //     text = '自有品牌'
      //     break
      //   case 'DI':
      //     text = '直接进口'
      //     break
      //   case 'DROPSHIPPING':
      //     text = '一件代发'
      //     break
      //   default:
      //     text = '暂无商品类型'
      // }
      return text
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  .card-content {
    position: relative;
    height: calc(100%);
    .title-button {
      position: absolute;
      right: 20px;
      margin-top: 25px;
    }
  }
}
.btn1 {
  margin-left: 10px;
}
.special {
  display: flex;
  align-items: center;
  margin-top: 15px;
  width: 100%;
}
.special .el-form-item__content {
  display: flex;
  align-items: center;
  width: 300px;
}
</style>
